<template>
  <el-card>
    <template #header>
      <div class="card-header">
        <span>个人中心</span>
      </div>
    </template>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-card class="profile-card">
          <template #header>
            <span>基本信息</span>
          </template>
          
          <el-form :model="profileForm" label-width="80px">
            <el-form-item label="用户名">
              <el-input v-model="profileForm.username" disabled />
            </el-form-item>
            <el-form-item label="昵称">
              <el-input v-model="profileForm.nickname" />
            </el-form-item>
            <el-form-item label="邮箱">
              <el-input v-model="profileForm.email" disabled />
            </el-form-item>
            <el-form-item label="电话">
              <el-input v-model="profileForm.phone" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="updateProfile">保存信息</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card class="password-card">
          <template #header>
            <span>修改密码</span>
          </template>
          
          <el-form :model="passwordForm" label-width="80px" :rules="passwordRules" ref="passwordFormRef">
            <el-form-item label="原密码" prop="oldPassword">
              <el-input v-model="passwordForm.oldPassword" type="password" show-password />
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
              <el-input v-model="passwordForm.newPassword" type="password" show-password />
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="changePassword">修改密码</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import request from '../components/utils/request'

// 基本信息表单
const profileForm = ref({
  username: '',
  nickname: '',
  email: '',
  phone: ''
})

// 密码表单
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码表单验证规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const passwordFormRef = ref(null)

// 组件挂载时获取用户信息
onMounted(() => {
  fetchUserProfile()
})

// 获取用户信息
const fetchUserProfile = () => {
  const userInfo = localStorage.getItem('userInfo')
  if (userInfo) {
    const user = JSON.parse(userInfo)
    profileForm.value = {
      username: user.username || '',
      nickname: user.nickname || '',
      email: user.email || '',
      phone: user.phone || ''
    }
  }
}

// 更新用户信息
const updateProfile = async () => {
  try {
    const response = await request.put('/user/profile', profileForm.value);
    if (response.code === 200) {
      ElMessage.success('信息更新成功');
      // 更新本地存储
      const userInfo = JSON.parse(localStorage.getItem('userInfo'));
      Object.assign(userInfo, profileForm.value);
      localStorage.setItem('userInfo', JSON.stringify(userInfo));
    } else {
      ElMessage.error(response.msg || '更新失败');
    }
  } catch (error) {
    ElMessage.error('更新失败');
  }
};

// 修改密码
const changePassword = async () => {
  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const response = await request.put('/user/password', {
          oldPassword: passwordForm.value.oldPassword,
          newPassword: passwordForm.value.newPassword
        });

        if (response.code === 200) {
          ElMessage.success('密码修改成功');
          passwordForm.value = {
            oldPassword: '',
            newPassword: '',
            confirmPassword: ''
          };
        } else {
          ElMessage.error(response.msg || '密码修改失败');
        }
      } catch (error) {
        ElMessage.error('密码修改失败');
      }
    }
  });
};
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.profile-card,
.password-card {
  height: 100%;
}
</style>